package com.lubase.wfengine.remote;

import com.alibaba.fastjson.JSON;
import com.lubase.wfengine.auto.entity.WfCallbackEntity;
import com.lubase.wfengine.auto.entity.WfTEventEntity;
import com.lubase.wfengine.model.OpenEventModel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public abstract class SendEventToRemoteService {

    @Autowired
    protected CacheManager cacheManager;
    protected final String cacheName = "wfengine";

    /**
     * 发送流程引擎事件到缓存
     *
     * @param serviceId
     * @param dataId
     * @param entity
     */
    public void sendWorkFlowEventToCache(String serviceId, String dataId, WfTEventEntity entity) {
        Cache cache = cacheManager.getCache(cacheName);
        String key = String.format("engine:%s:%s", serviceId, dataId);
        List<String> list = null;
        if (cache != null) {
            list = cache.get(key, List.class);
        }
        if (list == null) {
            list = new ArrayList<>();
        }
        list.add(JSON.toJSONString(entity));
        cache.put(key, list);
        log.info("发送engine事件到缓存： {}", JSON.toJSONString(list));
    }

    /**
     * 发送流程引擎核心事件
     *
     * @param serviceId
     * @param dataId
     */
    public abstract void sendWorkFlowEngineEvent(String serviceId, String dataId);

    /**
     * 发送更新业务表事件到消息队列
     *
     * @param serviceId
     * @param dataId
     * @param entity
     */
    public abstract void sendUpdateBisTableEvent(String serviceId, String dataId, WfCallbackEntity entity);

    /**
     * 发送流程引擎公开事件
     *
     * @param model
     */
    public abstract void sendWorkFlowOpenEvent(OpenEventModel model);

    /**
     * 将流程引擎公开事件放入缓存
     *
     * @param model
     */
    public void sendWorkFlowOpenEventToCache(OpenEventModel model) {
        if (model == null) {
            return;
        }
        Cache cache = cacheManager.getCache(cacheName);
        String key = String.format("open:%s:%s", model.getServiceId(), model.getDataId());
        List<String> list = null;
        if (cache != null) {
            list = cache.get(key, List.class);
        }
        if (list == null) {
            list = new ArrayList<>();
        }
        list.add(JSON.toJSONString(model));
        cache.put(key, list);
    }

    /**
     * 将缓存中的流程引擎公开事件放入消息队列
     *
     * @param serviceId
     * @param dataId
     */
    public abstract void sendWorkFlowOpenEventToMqFromCache(String serviceId, String dataId);
}
